<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib prefix="sys" tagdir="/WEB-INF/tags/sys"%>
<%@taglib uri="/WEB-INF/tlds/webui.tld" prefix="webui"%>


<webui:enum var="contentType" code="contentType"/>
<webui:enum var="exclusiveTypeEnum" code="exclusive"/>
<webui:enum var="mergerTypeEnum" code="mergerType"/>
<webui:enum var="cpNameTypeEnum" code="cpNameType"/>
<webui:enum var="orgEnum" code="OrgEnum" appendJs="true"/>
<script>
//用于显示组织名称
function tableOrgEnum(table,data){
	var logs = data.data.content;
	$(logs).each(function(index,element){
		var _self = this;
		var orgName = orgEnum[element.cpContent.orgId];
		Vue.set(_self,"orgName",orgName);
	});
	var contentCount = data.page.totalElements;
	if(!document.getElementById("table_length")){
		$("#grid_merger_paginate").parent().prev().append("<div id='table_length' style='float:left'></div>");
	}
	if (contentCount > 0) {
		$("#table_length").html("共"+contentCount+"条数据");
	} else {
		$("#table_length").html("");
	}
}
</script>
<webui:panel id="channelsSearch">
	<%-- -----------------筛选条件 start------------------ --%>
	<webui:form method="get" styleClass="form-horizontal" 
		name="declareSearchForm" id="declareSearchForm"
		action="${contextPath}/getUnitContentCPContent.action">
		<input type="hidden" name="orderBy" id="orderBy"/>
		<input type="hidden" name="field" id="field"/>
		<webui:select label="CP名称" styleClass="col-sm-4" labelClass="col-sm-4" 
			inputClass="col-sm-8" name="orgId" id="mergerType" lookup="${orgEnum}" 
			multiple="false">
		</webui:select>
		<webui:input label="片名" styleClass="col-sm-4" labelClass="col-sm-4"
			inputClass="col-sm-8" type="text" name="cpName">
		</webui:input>
		<webui:input label="归并名称" styleClass="col-sm-4" labelClass="col-sm-4"
			inputClass="col-sm-8" type="text" name="name">
		</webui:input>
		<webui:select label="内容类型" styleClass="col-sm-4" labelClass="col-sm-4" 
			inputClass="col-sm-8" name="contentType" id="contentTypeSelectList" lookup="${contentType}" 
			multiple="false">
		</webui:select>
		<webui:select label="是否独家" styleClass="col-sm-4" labelClass="col-sm-4" 
			inputClass="col-sm-8" name="exclusive" id="exclusiveType" lookup="${exclusiveTypeEnum}" 
			multiple="false">
		</webui:select>
		<webui:select label="归并状态" styleClass="col-sm-4" labelClass="col-sm-4" 
			inputClass="col-sm-8" name="mergerType" id="mergerType" lookup="${mergerTypeEnum}" 
			multiple="false">
		</webui:select>

		<div class="col-sm-12">
			<webui:datepicker label="申报时间"  styleClass="col-sm-5" name="startTime" labelClass="col-sm-4" 
				inputClass="col-sm-8" beginName="startDeclareTime" beginId="startDeclareTime" 
				endName="endDecalareTime" endId="endDecalareTime" duration="true">
			</webui:datepicker>
			<webui:datepicker label="上线时间"  styleClass="col-sm-5" name="startTime" labelClass="col-sm-4" 
				inputClass="col-sm-8" beginName="startOnLineTime" beginId="startOnLineTime" 
				endName="endOnLineTime" endId="endDecalareTime" duration="true">
			</webui:datepicker>
			<webui:button label="" type="button" styleClass="col-sm-2" onclick="grid_merger.filter()"
				labelClass="col-sm-1" inputClass="col-sm-3" buttonClass="btn-primary">
				查询
			</webui:button>
		</div>
	</webui:form>
	<%-- -----------------筛选条件 end------------------ --%>
	
	<%-- -----------------数据显示 start------------------ --%>
	<webui:table id="grid_merger"  dataUrl="${contextPath}/getUnitContentCPContent.action?sort=id,desc" dataload="tableOrgEnum"
	  datas="data.content" editorForm="#declareEditor" searchForm="#declareSearch">
		<webui:column editor="tableCheck" format="row.id" title="row.exclusive+','+row.unitContent" ></webui:column>
		<webui:column field="code" title="归并名称">
			<div v-if="row.unitContent != null">
				{{row.unitContent.name}}
			</div>
		</webui:column>
		<webui:column field="name" title="归并合计">
			<div v-if="row.unitContent != null">
				{{row.unitContent.contentNum }}
			</div>
		</webui:column>
		<webui:column field="name" title="片名">{{row.name }}</webui:column>
		<webui:column field="orgName" title="CP名称" >{{row.orgName}}</webui:column>
		<webui:column field="contentType" title="内容类型"  lookup="${contentType}">	{{row.contentTypeDesc}}</webui:column>
		<webui:column field="" title="是否独家">{{row.exclusive == 1 ? '独家':'非独家' }}</webui:column>
		<webui:column field="declareTime" title="申报时间">{{row.declareTime | moment("YYYY-MM-DD HH:mm:ss") }}</webui:column>
		<webui:column field="planOnlineTime" title="上线时间">{{row.planOnlineTime | moment("YYYY-MM-DD HH:mm:ss")}}</webui:column>
		<webui:column field="lastUpdateTime" title="修改时间">{{row.cpContent.lastUpdateTime | moment("YYYY-MM-DD HH:mm:ss")}}</webui:column>
		<webui:column field="ztePlayUrl" title="采纳状态">
			<div v-if="row.isAdopted == 0">未采纳</div>
			<div v-if="row.isAdopted == 1">已采纳</div>
			<div v-if="row.isAdopted == 2">待采纳</div>
		</webui:column>
		<webui:column style="text-align:rigth" title="操作"> 
			<a v-if="row.unitContent == null && row.cpContent.exclusive != 1" class="btn btn-xs btn-warning" v-bind:href="'javascript:onRowMerger('+row.id+',\''+row.name+'\',\''+row.orgId+'\','+row.exclusive+')'">归并</a>	
			<a v-if="row.unitContent != null && row.cpContent.exclusive != 1 && (row.unitContent.adoptCpContentId == null)" class="btn btn-xs btn-primary" 
				v-bind:href="'javascript:onEditAway('+row.cpContent.id+',\''+row.cpContent.name+'\',\''+row.unitContent.name+'\',\''+row.orgId+'\')'">脱离</a>
			<a v-if="row.cpContent.exclusive == 1 && row.unitContent == null" class="btn btn-xs btn-primary" v-bind:href="'javascript:affirmExclusive('+row.cpContent.id+',\''+row.cpContent.name+'\',\''+row.cpContent.orgId+'\')'">确认独家</a>
			<a v-if="row.cpContent.exclusive == 1" class="btn btn-xs btn-primary" v-bind:href="'javascript:cancelExclusive('+row.cpContent.id+',\''+row.cpContent.name+'\',\''+row.cpContent.orgId+'\')'">取消独家</a>	
		</webui:column>
	</webui:table>
	<%-- -----------------数据显示 end------------------ --%>
	<webui:button label="" type="button" styleClass="col-sm-3" labelClass="col-sm-1" 
		inputClass="col-sm-3" buttonClass="btn-primary" onclick="onBatchMerger()">
		批量归并
	</webui:button>
</webui:panel>
<!-- 归并窗口 -->
<div id="mergerDialog" class="modal fade" role="dialog"   aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content animated bounceInRight">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">
					<span aria-hidden="true">×</span><span class="sr-only">Close</span>
				</button>
				<h4 id="selectDialogTitle" class="modal-title">归并数据</h4>
			</div>
			<div class="modal-body" style="height:150px;">
				<webui:form method="get" styleClass="form-horizontal" id="mergerEditorForm">
					<input type="hidden" value="" name="id" id="editFormCpId" />
					<input type="hidden" value="" name="uId" id="unitId">
					<div style="height:125px;margin-top:-10px;" class="col-sm-12">
						<div class="col-sm-3" style="display: inline;padding-top:5px;">
							归并名称
						</div>
						<div class="col-sm-9">
						    <select  id="demoSelect"  style="width:100%;height:26px;" onchange="selectChange()">
						    </select>
						    <input  id="inputselect" type="text" onkeyup="refershSelect()" style="width:94%;height:26px;position: relative;top: -26px;outline: none;" />
						</div>
					</div>
				</webui:form>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-white" data-dismiss="modal">取消</button>
				<button type="button" class="btn btn-primary" onclick="saveMererName()">保存</button>
			</div>
		</div>
	</div>
</div>


<script>
$(function(){
	/******************************按照录入时间排序*************************************/
	var createOrderBy = "desc";
	$("#planOnlineTime_title").click(function(){
		$("#field").val("planOnlineTime");
		if(createOrderBy == "desc"){
			createOrderBy = "asc";
			$("#orderBy").val("asc");
		}else if(createOrderBy == "asc"){
			createOrderBy = "desc";
			$("#orderBy").val("desc");
		}
		if(!document.getElementById("onlineTimeOrderIcon")){
			$(this).append("<span id='onlineTimeOrderIcon' class='glyphicon'></span>");
		}
		if(document.getElementById("declareTimeOrderIcon")){
			$("#declareTimeOrderIcon").remove();
		}
		tableSort(createOrderBy,"onlineTime");
	});
	/******************************按照申报时间排序*************************************/
	var declareOrderBy = "desc";
	$("#declareTime_title").click(function(){
		$("#field").val("declareTime");
		if(declareOrderBy == "desc"){
			declareOrderBy = "asc";
			$("#orderBy").val("asc");
		}else if(declareOrderBy == "asc"){
			declareOrderBy = "desc";
			$("#orderBy").val("desc");
		}
		if(!document.getElementById("declareTimeOrderIcon")){
			$(this).append("<span id='declareTimeOrderIcon' class='glyphicon'></span>");
		}
		if(document.getElementById("onlineTimeOrderIcon")){
			$("#onlineTimeOrderIcon").remove();
		}
		tableSort(declareOrderBy,"declareTime");
	});
});

function tableSort(order,field){
	grid_merger.filter();
	if(order == "desc"){
		$("#"+field+"OrderIcon").removeClass("glyphicon-chevron-up");
		$("#"+field+"OrderIcon").addClass("glyphicon-chevron-down");
	}else if(order == "asc"){
		$("#"+field+"OrderIcon").removeClass("glyphicon-chevron-down");
		$("#"+field+"OrderIcon").addClass("glyphicon-chevron-up");
	}
	
}

//点击批量归并
function onBatchMerger(id,name,orgId,exclusive){
	var arrayList = grid_merger.getCheckboxTitleList();
	if (arrayList.length > 0){
		var flag = false;
		for(var i = 0; i < arrayList.length ; i++){
			var arr = arrayList[i].split(',');
			//alert(arr[0]+"    |||   "+(arr[1]=='null'));
			if (arr[0]!='false' || arr[1]!='null') {
				flag = true;
				break;
			}
		}
		if (flag) {
			alert("批量归并中，不能包含已归并数据和独家数据!!!");
		} else {
			var arrayId = grid_merger.getCheckboxListObj();
			var cpId = '';
			for(var i = 0; i < arrayId.length ; i++){
				cpId+=","+arrayId[i];
			}
			cpId = cpId.substring(1);
			$("#selectDialogTitle").html("批量归并");
			$("#editFormCpId").val(cpId);
			refershSelect();
			$("#mergerDialog").modal('show');
		}
	} else {
		alert("请选择要归并的CP！！！");
	}
}

//点击脱离mergerCp
function onEditAway(id,name,unitName,orgId){
	confirm("您确定要将\""+name+"\"脱离\""+unitName+"\"吗？",function(){
		$.ajax({
			method:'get',
			url:'${contextPath}/unitAway.action?id='+id,
			success:function(){
				grid_merger.reload();
				$("#mergerDialog").modal('hide');
				showMessage('提示', name+',脱离成功！');
			}	
		}); 	
	});
}

//选择发生改变时
function selectChange(){
	$("#unitId").val($("#demoSelect").val());
	$("#inputselect").val($("#item_"+$("#demoSelect").val()).attr("title"));
}
//刷新归并数据
function refershSelect(){
	var keyChar = $.trim($("#inputselect").val());
	$.ajax({
		method:'get',
		url:'${contextPath}/rest/unitContents/search/findByNameLike?name='+keyChar,
		success:function(data){
			var items = data._embedded.unitContents;
			//$("#selectDialogTitle").html(items[0].name);
			var str = "<option value='' hidden='true' ></option>";
			for (var i=0;i<items.length;i++){
				str += " <option id="+"item_"+items[i].id+" value="+items[i].id+" title="+items[i].name+">"+items[i].name+"</option>";
			}
			$("#demoSelect").html(str);
		}
	});
}
//归并保存事件
function saveMererName(){
	//alert("CP的Id="+$("#editFormCpId").val()+"\n 归并的ID="+$("#unitId").val()+"\n 归并名称="+$("#inputselect").val());
	var uId = $("#unitId").val();
	var mergerName = $("#inputselect").val();
	if (mergerName.length < 1){
		alert("请输入归并的名称");
		return ;
	}
	if (uId.length == 0) {
		var falgTitle = false;
		var uIdModel = '';
		$("#demoSelect option").each(function(i){
			if (mergerName == $(this).attr("title")){
				falgTitle = true;
				uIdModel = $(this).val();
			}
		});
		if (falgTitle) {
			uId = uIdModel;
			save(uId,mergerName);
			return;
			 /* BootstrapDialog.show({
		            title: '确认',
		            message: mergerName+'归并组已经存在，是否归并其中？',
		            type: BootstrapDialog.TYPE_WARNING,
		            buttons: [{
		                label: '是',
		                cssClass: 'btn-warning',
		                action: function(dialog) {
		                	uId = uIdModel;
						save(uId,mergerName);
		                	dialog.close();
							return;
		                }
		            }, {
		                label: '否',
		                action: function(dialog) {
		                	uId ='';
							save(uId,mergerName);
		                	dialog.close();
							return;
		                }
		            }]
		        }); */
		}else {
			uId ='';
			save(uId,mergerName);
		}
	}else{
		save(uId,mergerName);
	}
}
function save(uId,mergerName){
	var cpId = $("#editFormCpId").val();
	var arrayId = cpId.split(',');
	if (arrayId.length == 1) { //单个CP归并
		$.ajax({
			method:'post',
			url:'${contextPath}/mergerCP.action',
			data:{cpId:cpId,mergerName:mergerName,uId:uId},
			success:function(data){
				if(data.result==0){
					grid_merger.reload();
					$("#unitId").val('');
					$("#mergerDialog").modal('hide');
					showMessage('提示', '数据归并成功！');
				}else{
					showError("提示","归并失败！原因："+data.message);
				}
			}	
		});
	}
	if (arrayId.length > 1) { //批量归并
		var successNum = 0;
		for(var i = 0; i < arrayId.length ; i++){
			$.ajax({
				method:'post',
				async:false,
				url:'${contextPath}/mergerCP.action',
				data:{cpId:arrayId[i],mergerName:mergerName,uId:uId},
				success:function(data){
					if (uId == '' && i==0) {
						uId = data.data;
					}
					successNum=successNum+1;
					grid_merger.reload();
					$("#mergerDialog").modal('hide');
				}	
			});
		}
		if (successNum > 0) {
			$("#unitId").val('');
			showMessage('提示', '数据归并成功！');
		} else {
			$("#unitId").val('');
			showError('提示', '数据归并失败！');
		}
	}
}

//点击确认独家按钮
function affirmExclusive(id,name,orgid){
	confirm('确认  \"'+name+'\" 为独家数据吗?\n确认独家后将自动归并和采纳!!!', function(result){
		$.ajax({
			method:"get",
			url:'${contextPath}/affirmExclusive.action?id='+id+'&rowId='+id,
			success:function(){
				grid_merger.reload();
				showMessage('提示', name+'独家，确认成功！');  	
			}
		});	
    });
}

//取消独家按钮
function cancelExclusive(id,name,orgid){
	confirm('是否取消\"'+name+'\"为独家数据？取消以后将会变成非独家数据',function(result){
		$.ajax({
			method:"get",
			url:'${contextPath}/cancelExclusive.action?id='+id,
			success:function(){
				grid_merger.reload();
				showMessage('提示', name+'独家，取消成功！'); 
			}
		});
	});
}
//显示归并窗口
function onRowMerger(id,name,orgId,exclusive){
	$("#selectDialogTitle").html("正在归并\""+name+"\"");
	$("#inputselect").val("");
	$("#editFormCpId").val(id);
	refershSelect();
	$("#mergerDialog").modal('show');

	
}






</script>
